package com.pzh.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.usercenter.common.BaseResponse;
import com.pzh.usercenter.common.ErrorCode;
import com.pzh.usercenter.common.ResultUtils;
import com.pzh.usercenter.contant.UserConstant;
import com.pzh.usercenter.exception.BusinessException;
import com.pzh.usercenter.model.domain.User;
import com.pzh.usercenter.model.request.UserLoginRequest;
import com.pzh.usercenter.model.request.UserRegisterRequest;
import com.pzh.usercenter.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Tag(name = "用户接口")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 用户注册
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册",description = "根据注册信息注册用户")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"request is null");
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            return null;
        }

        long result = userService.userRegister(userAccount, userPassword, checkPassword,planetCode);
        return ResultUtils.success(result);
    }


    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public BaseResponse<User> doLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        User user = userService.doLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @Operation(summary = "用户注销")
    public BaseResponse<Integer> doLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    @GetMapping("/current")
    @Operation(summary = "获取当前用户信息")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        //查询用户数据
        Long id = currentUser.getId();

        User user = userService.getById(id);
        //返回脱敏数据
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);

    }

    /**
     * 管理员查询所有用户信息
     * @param username
     * @param request
     * @return
     */
    @GetMapping("/search")
    @Operation(summary = "管理员查询用户信息")
    public BaseResponse<List<User>> searchUser(String username,HttpServletRequest request) {
        // todo 用户登录存入的缓存导致变更数据时不生效
        if (!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"当前用户非管理员");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            //模糊查询
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> users = userList.stream()
                .map(user -> userService.getSafetyUser(user))
                .collect(Collectors.toList());
        return ResultUtils.success(users);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "更新用户信息")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request) {
        //判空
        if(user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取当前用户信息
        User loginUser = userService.getLoginUser(request);
        //更新 loginUser 信息为 user
        int res =  userService.updateUser(user,loginUser);
        //更新session todo 有问题
//        String sessionId = request.getSession().getId();
//        String redisKey = "yupao:userLogin:session" + sessionId;
//        redisTemplate.opsForHash().put(redisKey, "currentUser", user);
        return ResultUtils.success(res);
    }

    /**
     * 根据标签搜索用户
     * @param tagNameList
     * @return
     */
    @GetMapping("/search/tags")
    @Operation(summary = "根据标签搜索用户")
    public BaseResponse<List<User>> searchUserTags(@RequestParam(required = false) List<String> tagNameList) { //非必填项
        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(userList);
    }


    /**
     * 推荐用户
     * @param pageSize
     * @param pageNum
     * @param request
     * @return
     */
    @GetMapping("/recommend")
    @Operation(summary = "主页推荐用户")
    public BaseResponse<Page<User>> recommendUsers( long pageSize, long pageNum,HttpServletRequest request) {
        Page<User> userPage = userService.getRecommendUsers(pageSize,pageNum,request);
        return ResultUtils.success(userPage);
    }

    /**
     * 删除指定用户
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @Operation(summary = "删除用户")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id,HttpServletRequest request) {
        if (!userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"当前用户非管理员");
        }

        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 获取最匹配用户
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    @Operation(summary = "获取最匹配用户")
    public BaseResponse<List<User>> matchUsers( long num,HttpServletRequest request) {
        if(num <= 0 || num > 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        List<User> userList = userService.matchUsers(num,loginUser);
        return ResultUtils.success(userList);
    }

}
